<template>
  <div class="container">
    <topTitle titleText="考勤数据"></topTitle>

    <!--上传-->
    <div class="mainCon">
      <div class="createPayWin">
        <p>上传</p>
        <el-row class="toolbar" style="padding-bottom: 0">
          <el-form
            :model="formData"
            label-width="85px"
            ref="formData"
            :rules="formRules"
          >
            <el-row class="row-padding-bottom" style="text-align: left">
              <el-col>
                <el-form-item label="选择文件" prop="excel">
                  <span class="uploadBox el-input__inner">
                    <form id="salaryExcelForm">
                      <input
                        type="file"
                        id="salaryExcel"
                        name="multipartFile"
                        placeholder="placeholder"
                        @change="upLoadExcel"
                      />
                    </form>
                  </span>
                  导入的表格应与模板格式一致，
                  <el-link type="primary" @click="downLoad()"
                    >点击下载模板</el-link
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="row-padding-bottom">
              <el-button
                class="commonBut saveBtn"
                @click="toImportSalary"
                :loading="isAdd"
                >导入</el-button
              >
            </el-row>
          </el-form>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
import salaryTopTitle from '@/components/publicCom/salaryTopTitle'

export default {
  name: 'importSalary',
  components: {
    salaryTopTitle,
  },
  data() {
    var checkInput = (rule, value, callback) => {
      var that = this
      setTimeout(function () {
        var val = $('#salaryExcel').val()
        if (!val) {
          return callback(new Error('请选择需要导入的表格'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      createWay: '导入考勤',
      placeholder: '请选择Excel文件',
      formData: {},
      formRules: {
        excel: [
          {
            required: true,
            validator: checkInput,
            trigger: 'blur',
          },
        ],
      },
      isAdd: false,
    }
  },
  created() {},
  methods: {
    toImportSalary() {
      this.isAdd = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          //   this.year = this.formData.month.split("-")[0]; //年
          //   this.month = this.formData.month.split("-")[1]; //月
          var that = this
          var Filedata = $('#salaryExcel').val()

          if (!/\.(xls|xlsx)$/.test(Filedata)) {
            this.$message({
              message: 'excel类型必须是.xls,xlsx中的一种',
              type: 'warning',
            })
            this.isAdd = false
            $('#salaryExcel').val('')
            return
          }

          setTimeout(function () {
            //that.isAdd = true;
            that.uploadFileByAjaxSubmit(
              //   "api-su/cs/salary/expand/importExcel",
              'api-att/cs/att/expand/importatt',
              that.success,
              that.error
            )
          }, 500)
        } else {
          this.isAdd = false
          // this.$refs.detail.validateField('pictureIds')
        }
      })
    },
    upLoadExcel() {
      this.$refs.formData.validateField('excel')
    },
    success(data) {
      this.isAdd = false
      if (!data.hasError) {
        this.$message({
          message: data.msg,
          type: 'success',
        })
        $('#salaryExcel').val('')
      } else {
        this.$message({
          message: data.errorMsg,
          type: 'error',
        })
      }
    },
    //根据状态码判断是否是401
    error(XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.isAdd = false
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      let that = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        // data: {projectId: that.projectId},
        dataType: 'json',
        headers: { Authorization: 'Bearer ' + token },
        contentType: false,
        processData: false,
        success: function (data) {
          successCallBack(data)
          $('#salaryExcel').val('')
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
        //		resetForm: true
      }
      //	$("#uploadFileForm").ajaxSubmit(options);
      //$(".uploadFileForm").ajaxSubmit(options);
      //$("from").ajaxSubmit(options);
      //三种方式均可
      $('#salaryExcelForm').ajaxSubmit(options)
      // $(dom).ajaxSubmit(options);
      return false
    },
    downLoad() {
      window.location.href =
        'http://139.129.202.71/idcardread/考勤数据模板.xlsx'
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  top: 197px;
}

.el-form-item {
  margin-bottom: 28px;
}

.createPayWin {
  margin-top: 60px;
  text-align: center;
  margin-bottom: 0;
  padding-bottom: 70px;
  p {
    font-size: 28px;
    color: #333;
    font-family: '宋体';
    margin-bottom: 60px;
  }
  .el-form {
    display: inline-block;
    width: 460px;
    /deep/ .el-form-item__content {
      width: 340px;
    }
    /deep/ .el-input {
      width: 340px;
    }

    .commonBut {
      margin-top: 8px;
    }
    .goBack {
      margin-top: 22px;
      font-size: 14px;
      color: #999;
      cursor: pointer;
      i {
        vertical-align: middle;
      }
    }
    .createWay /deep/ input {
      font-size: 14px;
      color: #666;
      background: #bfc5cc;
      border: 1px solid #bfc5cc;
    }
    .companyName /deep/ input {
      border: none;
      color: #666;
    }
  }
  /deep/ .toolbar {
    padding: 0;
  }
  .uploadBox {
    line-height: 36px;
    width: 100%;
    text-align: left;
    /deep/ form {
      display: inline-block;
    }
  }
}

.errorNoticeBox {
  text-align: center;
  margin-bottom: 24px;
  i {
    color: red;
    font-size: 50px;
  }
}
.errorBox {
  line-height: 24px;
}
</style>
